<?php
// 还款
class repaymentControlPage extends commonControlPage 
{
    public function listModule() 
	{
        $opt = $_REQUEST['opt'];
        $opt = $opt ? $opt : 'list';
        call_user_func(array($this,"{$opt}Action"));
    }

	/*[所有经过复审的欠款记录 ， 已还款的不显示]*/
    private function listAction() 
	{        
        $where = "audit_state = '2' and price>arr_price ";
		$page = (int)$_GET['page_no'];
        $this->view->lists = $this->PrePageByURL('loan','loan_id',$where ,$page,'loan_id desc','app=repayment&mod=list&page_no=tpt');
        $this->showMainPage('admincp/repayment_list');
    }


	/*[还款可以直接通过无需审批]*/
    private function repaymentAction() 
	{
        $loan_id = (int)$_GET['loan_id'];
        $loan = $_ENV['db']->fetch("SELECT * FROM loan WHERE loan_id = '{$loan_id}'");
		//if ($loan['uid']!=$this->user['uid'] || $loan['audit_state']!=3)
		//财务账户可以对不是还不是本身账户的还款单进行还款 
		if ( $loan['audit_state']!=2)   $this->showMessage('请从还款列表中选择欠款单进行还款','back');

        //$node_id = $_ENV['config']['repayment_post_node'];
        if (POST && AJAX) 
		{
            $next_uid = (int)$_POST['next_uid'];
            $data = array();
            if (!preg_match('/^(\d|[1-9]\d{0,9})(\.\d{1,2})?$/',$_POST['price'])) {
                $this->outputJson(0,'金额输入格式不正确');
            }
            $data['price'] = $_POST['price'];   //还款金额
            // 检查指定的人是否具有操作权限
            //$cr = $_ENV['db']->fetch("SELECT * FROM admincp_member_perm WHERE uid = '{$next_uid}' AND node_id = '{$node_id}'");
            //if (!$cr) {
            //    $this->outputJson(0,'指定的下级操作员没有权限');
            //}
			
            // 判断总还款金额是否合法
            $price = 0;
            $tprice = $_ENV['db']->fetchCol("SELECT sum(price) as price FROM repayment WHERE loan_id = '{$loan_id}'");
            $price += $tprice;
            $price += $data['price'];

            if ($price > $loan['price']) {
                $this->outputJson(0,"已提交的所有的还款请求加上当前请求总金额超出了本单欠款金额");
            }

            $data['co_member_id'] = $next_uid;
            $data['loan_id']      = $loan_id;
            $data['uid']          = $this->user['uid'];
            $data['username']     = $this->user['username'];
            $data['audit_state']  = '1';
            $data['dateline']     = time();
			InsertTable('repayment',$data);


			$_ENV['db']->runSql("update loan set arr_price = arr_price+".$data['price']." where loan_id = '{$loan['loan_id']}'");
			$_ENV['db']->runSql("update loan set audit_state='4'  where arr_price>=price and loan_id = '{$loan['loan_id']}'");
            $_ENV['db']->runSql("update admincp_member_detail set loan_price=loan_price-".$data['price'] . " where `uid` = '{$loan['uid']}'" );
			
            $this->outputJson(1,'操作成功');
        }
		//取的当前还款人的历史还款金额
		$this->view->currprice = $_ENV['db']->fetchCol("SELECT loan_price  FROM admincp_member_detail WHERE uid = '{$loan['uid']}'");
        // 选择下级操作人列表
        //$users = $_ENV['db']->fetchAll("SELECT m.username,m.nickname,m.uid FROM `admincp_member` as m LEFT JOIN admincp_member_perm as p ON m.uid=p.uid WHERE p.node_id = '{$node_id}'");
        //$this->view->users = $users;
		$this->view->loan = $loan;
        $this->showMainPage('admincp/repayment_post');
    }

	/*[]审核和复审功能  暂时屏蔽*/
    public function __call($func,$args) 
	{
        if (substr($func,0,5) == 'audit' && substr($func,5,1) < 2) 
		{
            $step = substr($func,5,1);
            $rid = (int)$_GET['rid'];
            if ($rid) 
			{
				/*[提交的还款记录]*/
                $repayment = $_ENV['db']->fetch("SELECT * FROM repayment WHERE rid = {$rid}");
                if (!$repayment) 
				{
                    $this->showMessage('找不到指定的欠款记录','back');
                }
				/*[还款单对应的还款记录]*/
				 $loan = $_ENV['db']->fetch("SELECT * FROM loan WHERE loan_id ='{$repayment['loan_id']}'");
				 if (!$loan) 
				 {
                   $this->showMessage('找不到指定的还款记录','back');
                 }

                /*if ((!$repayment['co_member_id'] != $this->user['uid'] && !in_array($this->user['uid'],$_ENV['config']['superadmin']))) {
                    $this->showMessage('找不到指定的还款记录','back');
                }*/

                $node_id = $_ENV['config']['repayment_audit_nodes'][$step];
                
                $param = array();
                $param['audit_state'] = $step + 1;
                $param["audit{$step}_uid"] = $this->user['uid'];
                $param["audit{$step}_username"] = $this->user['username'];
                $param["audit{$step}_dateline"] = time();

                if (POST && AJAX) 
				{
                    if ($repayment['audit_state'] != $step) 
					{
                        $this->outputJson(0,'没有权限操作');
                    }
                    switch($step) 
					{
                        case 1:
							//暂时去掉还款审核，所以将下级操作权限验证屏蔽
                            //$next_uid = (int)$_POST['next_uid'];
                            //$cr = $_ENV['db']->fetch("SELECT * FROM admincp_member_perm WHERE uid = '{$next_uid}' AND node_id = '{$node_id}'");
                            //if (!$cr) 
							//{
                            //    $this->outputJson(0,'指定的下级操作员没有权限');
                            //}
                            $param['co_member_id'] = '0' ; //$next_uid;
                        break;
                        case 2:
                            $param['co_member_id'] = '0';
                        break;
                    }

                    $setsql = $this->buildSql($param);
                    $_ENV['db']->runSql("update repayment {$setsql} where rid = '{$rid}'");
                    
					//if ($step==2) 
					if ($step==1)
					{   //暂时屏蔽还款审批，所以在审核时更改用户还款金额
                        $_ENV['db']->runSql("update loan set arr_price = arr_price+".$repayment['price']." where loan_id = '{$loan['loan_id']}'");
                        $_ENV['db']->runSql("update admincp_member_detail set loan_price=loan_price-".$repayment['price'] . " where `uid` = '{$loan['loan_id']}'" );
                    }

                    $this->outputJson(1,'操作成功');
                }

                // 下级操作员列表
                $users = $_ENV['db']->fetchAll("SELECT m.username,m.nickname,m.uid FROM `admincp_member` as m LEFT JOIN admincp_member_perm as p ON m.uid=p.uid WHERE p.node_id = '{$node_id}'");
                // 获取当前欠款单用户历史总欠款多少
                $loan_price = $_ENV['db']->fetchCol("SELECT loan_price FROM admincp_member_detail WHERE uid = '{$loan['uid']}'");

                $this->view->repayment = $repayment;
                $this->view->users = $users;
                $this->view->loan = $loan;
                $this->view->loan_price = number_format($loan_price,2);
                $this->view->step = $step;
                $this->showMainPage("admincp/repayment_audit_desc");
            } 
			else 
			{
                $total = $_ENV['db']->fetchCol("SELECT count(1) FROM repayment WHERE audit_state = {$step}");
                
                $pager = new class_pager();
                $pager->setConfig((int)$_GET['page_no'],$total);
                $pager->setUrl('?app=repayment&mod=audit'.$step.'&page_no=tpt','tpt');

                $lists = $_ENV['db']->fetchAll("SELECT * FROM repayment WHERE audit_state = '{$step}' order by rid desc LIMIT ".$pager->getLimit()." OFFSET ".$pager->getOffset());

                $this->view->page = $pager->output();
                $this->view->lists = $lists;
                $this->showMainPage('admincp/repayment_audit_list');
            }
        } 
		else 
		{
            parent::__call($func,$args);
        }
    }
}